package com.design.patterns;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察者主题对象
 */
interface Subject {

    /**
     * 订阅操作
     */
    void attach(Observer observer);

    /**
     * 取消订阅操作
     */
    void detach(Observer observer);

    /**
     * 通知变动
     */
    void notifyChanged();
}

/**
 * 观察者订阅人对象
 */
interface Observer {

    /**
     * 接收变动通知
     */
    void update();
}

class RealSubject implements Subject {
    private List<Observer> observerList = new ArrayList<Observer>();

//    @Override
    public void attach(Observer observer) {
        observerList.add(observer);
    }

//    @Override
    public void detach(Observer observer) {
        observerList.remove(observer);
    }

//    @Override
    public void notifyChanged() {
        for (Observer observer : observerList) {
            observer.update();
        }
    }

}

class RealObject implements Observer {
//    @Override
    public void update() {
        System.out.println("接收到了通知");
    }
}



public class ObserverPattern {

    public static void main(String[] args) {
        Subject subject = new RealSubject();
        Observer observer = new RealObject();
        subject.attach(observer);
        subject.notifyChanged();
    }
}
